<template>
  <div class="article-page">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>面经后台</el-breadcrumb-item>
      <el-breadcrumb-item>面经管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="never" border="false">
      <template #header>
        <div class="header">
          <span>共 {{total}} 条记录</span>
          <el-button
            icon="el-icon-plus"
            size="small"
            type="primary"
            @click="openDrawer('add')"
            round
          >
            添加面经
          </el-button>
        </div>
      </template>
      <!-- el-table的使用 当el-table元素中注入data对象数组后，
      在el-table-column中用prop属性来对应对象中的键名即可填入数据，
      用label属性来定义表格的列名。可以使用width属性来定义列宽。-->
      <el-table :data="list" style="width: 100%">
        <el-table-column prop="stem" label="标题" width="400">
        </el-table-column>
        <el-table-column prop="creator" label="作者"> </el-table-column>
        <el-table-column prop="likeCount" label="点赞"> </el-table-column>
        <el-table-column prop="views" label="浏览数"> </el-table-column>
        <el-table-column prop="createdAt" label="更新时间"> </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template #default="{ row }">
            <div class="actions">
              <i class="el-icon-view" @click="openDrawer('preview', row)"></i>
              <i
                class="el-icon-edit-outline"
                @click="openDrawer('edit', row)"
              ></i>
              <i class="el-icon-delete" @click="delArticle(row.id)"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 当页码变更时重新发起请求拿新数据 -->
      <!-- total 总条数  current-page 当前页  current-change 当前页修改事件 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page="current"
        @current-change="handleCurrentChange"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 抽屉区域
         1. title="我是标题"
         2. :visible 控制显示隐藏
         3. :direction="direction"  控制方向
         4. :before-close="handleClose" 关闭抽屉前的处理逻辑 (比如：询问客户是否真的要关闭？)
         5. size="60%" 窗体所占的区域多宽
-->
    <el-drawer
      :title="drawerTitle"
      :visible.sync="isShowDrawer"
      direction="rtl"
      :before-close="handleClose"
      size="60%"
    >
      <div v-if="type === 'preview'" class="article-preview">
      <h5>{{ form.stem }}</h5>
      <div v-html="form.content"></div>
    </div>
      <el-form v-else ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="stem">
          <el-input v-model="form.stem" placeholder="输入面经标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <!-- 富文本编辑器 -->
          <!-- 小难点 非element-ui表单元素 无法自动校验, 结合form表单验证单个数据的方法进行校验 -->
            <quill-editor @blur="$refs.form.validateField('content')" v-model="form.content" ref="myQuillEditor"></quill-editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">确认</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { getArticleList, createArticle, removeArticle, getArticleDetail, updateArticle } from '@/api/article'
// 富文本编辑器的使用 装包 ->  导入  -> 标签使用

import { quillEditor } from 'vue-quill-editor'
// require styles
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

// 渲染页面
// 1. 封装接口
// 2. 导入接口调用接口
// 3. 数据放在data里 然后v-for 渲染

// 封装一个函数处理Drawer组件出现隐藏
export default {
  name: 'ArticleIndex',
  components: {
    quillEditor
  },
  data () {
    return {
      current: 1,
      pageSize: 10,
      list: [],
      total: 0,
      isShowDrawer: false,
      type: 'add',
      form: {
        stem: '',
        content: ''
      },
      rules: {
        stem: [
          { required: true, message: '请输入标题' }
        ],
        content: [
          { required: true, message: '请输入内容' }
        ]
      }
    }
  },
  computed: {
    drawerTitle () {
      let title = '标题'
      if (this.type === 'add') title = '添加面经'
      if (this.type === 'preview') title = '查看面经'
      if (this.type === 'edit') title = '编辑面经'
      return title
    }
  },
  created () {
    this.getList()
  },
  methods: {
    async getList () {
      const res = await getArticleList({
        current: this.current,
        pageSize: this.pageSize
      })
      console.log(res)
      this.list = res.data.rows
      this.total = res.data.total
    },
    handleCurrentChange (current) {
      console.log(current)
      this.current = current
      this.getList()
    },
    async openDrawer (type, row) {
      console.log(type, row)
      this.type = type
      this.isShowDrawer = true
      // 非新增的时候去获取详情
      if (type !== 'add') {
        const res = await getArticleDetail(row.id)
        // this.form = res.data
        this.form = {
          ...res.data
        }
        // 写法2 不调用接口
        // this.form.stem = row.stem
        // this.form.content = row.content
        // this.form = {
        //   ...row
        // }
      }
    },
    // 关闭  Drawer
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          this.closeDrawer()
          done()
        })
        .catch((_) => {})
    },
    // 提交
    async submit () {
      try {
        await this.$refs.form.validate()
        // 下面就是校验通过的
        if (this.type === 'add') {
          await createArticle(this.form)
          this.$message.success('创建成功')
        }
        if (this.type === 'edit') {
          await updateArticle({
            id: this.form.id,
            stem: this.form.stem,
            content: this.form.content
          })
          this.$message.success('修改成功')
        }
        this.closeDrawer()
        // 页码改成第一页 再请求
        this.current = 1
        this.getList()
      } catch (error) {
        console.log(error)
      }
    },
    // 删除
    async delArticle (id) {
      await removeArticle(id)
      this.$message.success('删除成功')
      // 删除的是当前页最后一条,那么把current 减一 再掉接口
      if (this.list.length === 1 && this.current > 1) {
        this.current--
      }
      // 重新渲染
      this.getList()
    },
    // 关闭drawer 清空数据
    closeDrawer () {
      this.isShowDrawer = false
      if (this.type !== 'preview') {
        this.$refs.form.resetFields()
      }

      this.form = {
        stem: '',
        content: ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 25px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
  }
  .actions {
    font-size: 18px;
    display: flex;
    justify-content: space-around;
    color: #666;
    > i:hover {
      color: rgba(114, 124, 245, 1);
      cursor: pointer;
    }
  }
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
.el-breadcrumb {
  margin-top: 10px;
}
.el-form {
  padding-right: 40px;
}
.quill-editor {
  ::v-deep .ql-editor {
    height: 300px;
  }
}
.el-rate {
  padding: 10px 0;
}
.article-preview {
  padding: 0 40px 40px 40px;
  > h5 {
    font-size: 20px;
    color: #666;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 30px;
    margin: 0 0 20px 0;
  }
}
</style>
